package com.atguigu.yygh.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.orders.service.OrderInfoService;
import com.atguigu.yygh.orders.service.PaymentInfoService;
import com.atguigu.yygh.orders.service.RefundInfoService;
import com.atguigu.yygh.orders.service.WeixinService;
import com.atguigu.yygh.orders.utils.ConstantPropertiesUtils;
import com.atguigu.yygh.orders.utils.HttpClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeixinServiceImpl implements WeixinService {
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RefundInfoService refundInfoService;

    //生成微信二维码
    @Override
    public Map createNative(Long orderId) {

        //1 支付记录表添加数据
        //根据订单号查询订单
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        if (orderInfo == null) {
            throw new YyghException(20001, "订单不存在");
        }
        paymentInfoService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());

        try {
            //2 调用微信接口，得到二维码地址等信息
            //封装传递微信地址参数
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID); //公众号id
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER); //商户号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr()); //随机字符串，调用工具类

            Date reserveDate = orderInfo.getReserveDate();
            String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
            String body = reserveDateString + "就诊" + orderInfo.getDepname();
            paramMap.put("body", body);//扫码后手机显示内容

            paramMap.put("out_trade_no", orderInfo.getOutTradeNo()); //订单流水号
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");//TODO 为了测试  支付金额
            paramMap.put("spbill_create_ip", "127.0.0.1");  //终端ip
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");//回调地址
            paramMap.put("trade_type", "NATIVE"); //二维码类型
            //请求微信生成二维码接口
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置post请求相关参数
            //微信支付要求传递参数xml格式
            //把封装map集合变成xml，加密处理，传输
            String xml = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);
            client.setXmlParam(xml);
            //支持https协议
            client.setHttps(true);
            //发送
            client.post();

            //调用微信接口，返回数据,xml格式的数据
            String resultXml = client.getContent();
            System.out.println("微信二维码：" + resultXml);
            //把xml格式数据转换map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(resultXml);

            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));  //微信二维码地址

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new YyghException(20001, "生成二维码失败");
        }
    }

    //调用微信接口查询支付状态
    @Override
    public Map queryPayStatus(Long orderId, String paymentType) {
        //1 根据orderId查询订单信息
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        if (orderInfo == null) {
            throw new YyghException(20001, "订单不存在");
        }
        try {
            //2 封装微信接口需要数据
            Map paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

            //3 调用微信接口，传递数据，设置参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            //4 获取微信接口返回数据
            String xml = client.getContent();
            System.out.println("支付状态返回xml: " + xml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            return resultMap;

        } catch (Exception e) {
            e.printStackTrace();
            throw new YyghException(20001, "查询失败");
        }
    }

    //退款
    @Override
    public Boolean refund(Long orderId) {
        //1 根据订单号查询订单支付记录信息
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        PaymentInfo paymentInfo = paymentInfoService.getOne(wrapper);
        //2.添加退款信息到退款表
        RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
        //判断退款订单数据是否已经完成退款
        if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus()) {
            return true;
        }
        try {
            //3 调用微信退款接口
            //封装微信接口需要数据
            Map<String, String> paramMap = new HashMap<>(8);
            paramMap.put("appid", ConstantPropertiesUtils.APPID);       //公众账号ID
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);   //商户编号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id", paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no", paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no", "tk" + paymentInfo.getOutTradeNo()); //商户退款单号
            //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");
            paramMap.put("refund_fee", "1");

            //设置接口和参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.setCert(true);//退款证书
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);//证书密码 商户key
            //发送post请求
            client.post();

            //4、返回退款数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //根据微信退款接口返回数据 判断:退款是否成功
            //如果退款成功 更新退款纪录状态2
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
